package com.blkan.calculator.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blkan.calculator.history.HistoryItem;
import com.blkan.calculator.history.HistoryRepository;

import java.util.List;
import java.util.UUID;

public class SqliteHelper extends SQLiteOpenHelper {


    private static final String DB_NAME = "history.db";
    private static final String TABLE_NAME_HISTORY = "history";
    private static final String CREATE_SQL = "create table " +
            TABLE_NAME_HISTORY + " (id integer primary key autoincrement, ans text, input text, result text, uuid text);";

    public SqliteHelper(@Nullable Context context) {
        super(context, DB_NAME, null, 1);
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_SQL);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void insert(HistoryItem item)
    {

        ContentValues values = new ContentValues();
        values.put("ans", item.getAns());
        values.put("input", item.getInput());
        values.put("result", item.getResult());
        values.put("uuid", item.getUuid().toString());
        getReadableDatabase().insert(TABLE_NAME_HISTORY, null, values);
    }

    public void delete(UUID uuid)
    {
        getReadableDatabase().delete(TABLE_NAME_HISTORY, "uuid=?", new String[]{uuid.toString()});
    }

    public void deleteAll()
    {
        getReadableDatabase().delete(TABLE_NAME_HISTORY, null, null);
    }


    public void readAndStoreData()
    {
        List<HistoryItem> historyItems = HistoryRepository.getInstance().getHistoryItems();
        historyItems.clear();
        String query = "SELECT * FROM " + TABLE_NAME_HISTORY;
        Cursor cursor = getReadableDatabase().rawQuery(query, null);
        if(cursor.getCount() != 0)
        {
            cursor.moveToFirst();
            do {
                String ans = cursor.getString(1);
                String input = cursor.getString(2);
                String result = cursor.getString(3);
                UUID uuid = UUID.fromString(cursor.getString(4));
                HistoryItem item = new HistoryItem(ans,input,result,uuid);
                historyItems.add(item);
            }while (cursor.moveToNext());
        }


    }


}
